package com.guo.pet_store.admin.controller;

import com.guo.pet_store.admin.pojo.User;
import com.guo.pet_store.admin.service.UserService;
import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    UserService userService;
    @GetMapping
    public String toLogin(){
        return "admin/login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username
                        ,@RequestParam String password,
                        HttpSession session, RedirectAttributes redirectAttributes){

        User user = userService.checkUser(username,password);
        if (user!=null){
            session.setAttribute("user",user);
            return "redirect:/admin/pets";
        }else {
            redirectAttributes.addFlashAttribute("message","用户名或者密码错误");
            return "redirect:/admin";
        }
    }

    @GetMapping("/loginToIndex")
    public String IndexLogin(){
        return "login";
    }

    //登陆后返回index页面
    @PostMapping("/loginToIndex")
    public String loginToIndex(@RequestParam String username
            ,@RequestParam String password,@RequestParam String check,Model model,
                        HttpSession session, RedirectAttributes redirectAttributes){
        //判断验证码是否错误
        if (! session.getAttribute("randCheckCode").toString().equalsIgnoreCase(check)) {
            model.addAttribute("message","验证码错误!");
            return "login";
        }


        User user = userService.checkUser(username,password);
        if (user!=null){
            session.setAttribute("user",user);
            return "redirect:/index";
        }else {
            redirectAttributes.addFlashAttribute("message","用户名或者密码错误");
            return "redirect:/car";
        }
    }
}
